package org.lds.message.center.plugin.core.remote;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.lds.message.center.common.enums.ErrorEnum;
import org.lds.message.center.common.exception.BusinessException;
import org.lds.message.center.common.model.ResultDTO;
import org.lds.message.center.common.model.request.GetTemplateAdminRequest;
import org.lds.message.center.common.model.request.RegisterChannelAdminRequest;
import org.lds.message.center.common.model.response.GetTemplateAdminResponse;
import org.lds.message.center.common.util.AssertUtil;
import org.lds.message.center.common.util.RestUtil;
import org.lds.message.center.plugin.core.constant.PluginCoreConstant;
import org.lds.message.center.plugin.core.properties.RemoteProperties;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.ParameterizedTypeReference;

import java.util.Objects;

@Getter
@RequiredArgsConstructor
public class RemoteService {
    private final RemoteProperties remoteProperties;

    @Cacheable(cacheNames = PluginCoreConstant.CACHE_NAME)
    public GetTemplateAdminResponse getTemplate(String appName, String templateName) {
        ResultDTO<GetTemplateAdminResponse> resultDTO = RestUtil.post(remoteProperties.getGetTemplateUrl(), new GetTemplateAdminRequest(appName, templateName), new ParameterizedTypeReference<ResultDTO<GetTemplateAdminResponse>>() {});
        AssertUtil.assertTrue(Objects.nonNull(resultDTO), ErrorEnum.REST_FAIL);
        if (!resultDTO.isSuccess()) throw new BusinessException(resultDTO.getCode(), resultDTO.getMessage());
        return resultDTO.getData();
    }

    @CacheEvict(cacheNames = PluginCoreConstant.CACHE_NAME)
    public void clearTemplateCache(String appName, String templateName) {
    }

    public Long registerChannel(String type, String name, String desc, String healthUrl) {
        ResultDTO<Long> resultDTO = RestUtil.post(remoteProperties.getRegisterChannelUrl(), new RegisterChannelAdminRequest(type, name, desc, healthUrl), new ParameterizedTypeReference<ResultDTO<Long>>() {});
        AssertUtil.assertTrue(Objects.nonNull(resultDTO), ErrorEnum.REST_FAIL);
        if (!resultDTO.isSuccess()) throw new BusinessException(resultDTO.getCode(), resultDTO.getMessage());
        return resultDTO.getData();
    }

}
